package com.rt.easyjava.base.modules.timerjob.service.job.jobStrategy.strategy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rt.easyjava.common.config.SpringContextBaseHolder;
import com.rt.tmpt.service.utils.SpringContextHolder;
import com.rt.easyjava.base.modules.timerjob.dto.TmptTimerBizDto;
import com.rt.easyjava.base.modules.timerjob.service.job.jobStrategy.JobStrategy;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.utils.others.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 远程调用
 */
@Slf4j
public class HttpRemoteJobStrategy extends JobStrategy {

    public HttpRemoteJobStrategy(TmptTimerBizDto tmptTimerBizDto,Result typeResult) {
        super.tmptTimerBizDto = tmptTimerBizDto;
        super.typeResult = typeResult;
    }

    @Override
    protected String job() throws Exception {
        String className = tmptTimerBizDto.getClassName();
        String param = tmptTimerBizDto.getParam();

        String url = className;
        RestTemplate restTemplate =  SpringContextBaseHolder.getBean("restTemplate");
        // 参数
        String method = "get";
        Map<String, Object> paramMap = new HashMap<>();
        if (!StringUtils.isNull(param)) {
            paramMap = (Map) JSON.parse(param);
            if (!StringUtils.isNull(paramMap.get("method"))) {
                method = (String) paramMap.get("method");
            }
        }
        String resultJO = null;
        // method:get
        if ("get".equalsIgnoreCase(method)) {
            resultJO = restTemplate.getForObject(url, String.class);
        }
        // method:post
        else {
            JSONObject postData = (JSONObject)JSONObject.parse(param);
            resultJO = restTemplate.postForEntity(url, postData, String.class).getBody();
        }
        String jsonStringResult = resultJO;
        if (!Strings.isBlank(jsonStringResult) && jsonStringResult.length() > 1000) {
            jsonStringResult = jsonStringResult.substring(0, 1000);
        }

        return jsonStringResult;
    }
}
